package com.quanyan.club.service.impl;


import com.alibaba.dubbo.common.json.JSONObject;
import com.alibaba.dubbo.rpc.RpcException;
import com.google.common.collect.Lists;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.quanyan.activity.entity.ActivityInfo;
import com.quanyan.activity.response.RespActivityPoster;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.req.ReqClubMemberAccountStreamPage;
import com.quanyan.club.entity.vo.req.ReqClubMemberRecharge;
import com.quanyan.club.entity.vo.resp.*;
import com.quanyan.club.mapper.*;
import com.quanyan.club.service.ActivityCRUDService;
import com.quanyan.club.service.ClubFinanceMgmService;
import com.quanyan.club.service.ClubWidthdrawService;
import com.quanyan.club.service.CppService;
import com.quanyan.club.util.NumberGenerator;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.*;
import com.quanyan.common.vo.resp.RespCity;
import com.quanyan.common.vo.resp.RespDistrict;
import com.quanyan.orderpay.request.ReqOrderSave;
import com.quanyan.orderpay.request.ReqPayInfo;
import com.quanyan.orderpay.request.ReqProductDetail;
import com.quanyan.orderpay.response.RespPreOrder;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.place.entity.PlaceDubboProvider;
import com.quanyan.search.utils.Constant;
import com.quanyan.statium.api.resp.RespGameDetail;
import com.quanyan.statium.service.StadiumOpenService;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;

import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

/**
 * Created by zhuo.shi on 2016/6/7.
 */
@Service
public class ClubFinanceMgmServiceImpl extends BaseServiceImpl implements ClubFinanceMgmService {

    private static final Logger logger = LoggerFactory.getLogger(ClubFinanceMgmServiceImpl.class);

    @Autowired
    private TbClubOnlineAccountStreamMapper clubOnlineAccountStreamMapper;
    @Autowired
    private TbClubOfflineAccountStreamMapper clubOfflineAccountStreamMapper;
    @Autowired
    private TbClubOfflineMemberAccountMapper clubOfflineMemberAccountMapper;
    @Autowired
    private TbClubOfflineMemberAccountStreamMapper clubOfflineMemberAccountStreamMapper;
    @Autowired
    private TbClubOnlineMemberAccountMapper clubOnlineMemberAccountMapper;
    @Autowired
    private TbClubOnlineMemberAccountStreamMapper clubOnlineMemberAccountStreamMapper;
    @Autowired
    private ClubAccountExtendMapper clubAccountExtendMapper;
    @Autowired
    private TbClubActivitySettlementMapper clubActivitySettlementMapper;
    @Autowired
    private TbSignUserMapper signUserMapper;
    @Autowired
    private TbClubActivityMapper clubActivityMapper;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    private TbClubMemberMapper clubMemberMapper;
    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private TbClubMsgConsumerRecordMapper clubMsgConsumerRecordMapper;
    //rpc服务
    @Autowired
    private OrderPayService orderPayService;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private ClubWidthdrawService clubWidthdrawService;
    @Autowired
    private CppService cppService;
    @Autowired
    private ActivityOpenService activityOpenService;
    @Autowired
    private TbActivityPosterMapper posterMapper;

    @Autowired
    private StadiumOpenService stadiumOpenService;
    @Autowired
    private TbActivityMapper tbActivityMapper;
    @Autowired
    private PlaceClient placeClient;
    @Autowired
    private ClubActivityCRUDMapper clubActivityCRUDMapper;

    //充值成功回调接口
    @Value("${club_recharge_call_back_pay_success}")
    private String clubRechargeCallBackPaySuccess;
    //关闭支付回调接口
    @Value("${club_recharge_call_back_pay_close}")
    private String clubRechargeCallBackPayClose;
    //充值异常退款回调接口
    @Value("${club_recharge_apply_refund}")
    private String clubRechargeApplyRefund;
    //充值异常退款成功回调接口
    @Value("${club_recharge_refund_success}")
    private String clubRechargeRefundSuccess;

    /**
     * 俱乐部财务管理主页
     *
     * @param clubId 俱乐部ID
     */
    @Override
    public RespClubFmgIndexPage clubFmgIndexPage(@NotNull Integer clubId, String appVersion) {
        RespClubFmgIndexPage indexPage = new RespClubFmgIndexPage();
        TbClub club = clubMapper.selectByPrimaryKey(clubId);
        if (club == null || club.getIsDelete() == Constants.IS_DELETE_TRUE) {
            return null;
        }
        indexPage.setClubLogUrl(club.getLogoUrl());
        indexPage.setClubName(club.getClubName());
        indexPage.setUsabeWithdrawFund(clubWidthdrawService.getUsableWidthdrawAmount(clubId));
        indexPage.setClubTotalFund(this.getClubOnlineFund(clubId, null, null).add(this.getClubOfflineFund(clubId, null, null)));
        indexPage.setClubMemberTotalFund(this.getClubMemberTotalFund(clubId, appVersion));
        indexPage.setClubUnsettlmentFund(this.getClubUnsettlmentActivityTotalFund(clubId));
        return indexPage;
    }

    /**
     * 获取俱乐部月度结算活动收入流水列表    （分页）
     *
     * @param clubId   俱乐部ID
     * @param month    统计的月份
     * @param pageNo   页码
     * @param pageSize 每页记录数
     */
    @Override
    public List<RespClubFinanceBillDetail> getClubFinanceBillDetails(@NotNull Integer clubId, @NotNull @DateTimeFormat(pattern = "yyyy-MM") Date month,
                                                                     Integer pageNo, Integer pageSize) {
        List<RespClubFinanceBillDetail> details = new ArrayList<>();
        TbClubActivitySettlementExample settlementExample = new TbClubActivitySettlementExample();  //查询出一个月内某俱乐部已结算的活动
        settlementExample.createCriteria().andClubIdEqualTo(clubId)
                .andCreateTimeGreaterThanOrEqualTo(month).andCreateTimeLessThan(DateUtils.addMonth(month, 1));
        settlementExample.setOrderByClause(" create_time desc");
        settlementExample.setLimit(Limit.buildLimit(pageNo, pageSize));
        List<TbClubActivitySettlement> settlements = clubActivitySettlementMapper.selectByExample(settlementExample);
        for (TbClubActivitySettlement settlement : settlements) {
            int type = settlement.getType();
            if (type == 1) {         //俱乐部内部活动
                RespClubFinanceBillDetail respClubFinanceBillDetail =
                        getClubFinanceBillDetail(settlement.getActivityId(),
                                settlement.getClubId(), Constants.IS_YES);
                if (respClubFinanceBillDetail != null) {
                    details.add(respClubFinanceBillDetail);
                }
            }
            if (type == 2) {         //俱乐部赛事活动
                RespClubFinanceBillDetail respClubGameBillDetail = getClubGameFinanceBillDetail(settlement.getActivityId(), settlement.getClubId());
                if (respClubGameBillDetail != null) {
                    details.add(respClubGameBillDetail);
                }
            }
//            RespClubFinanceBillDetail detail = new RespClubFinanceBillDetail();
//            //活动基本信息
//            detail.setActivityId(settlement.getActivityId());
//            ActivityInfo activity = activityOpenService.queryOneActivityById(settlement.getActivityId());
//            if (activity != null) {
//                TbActivityPoster poster = posterMapper.selectByPrimaryKey(activity.getPosterPicId());
//                detail.setAvatar(poster.getUrl());
//                detail.setActivityName(activity.getName());
//
//                TbClubActivityExample example = new TbClubActivityExample();
//                example.createCriteria().andActivityIdEqualTo(activity.getId())
//                        .andClubIdEqualTo(clubId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
//                List<TbClubActivity> clubActivityList = clubActivityMapper.selectByExample(example);
//                if (clubActivityList != null && clubActivityList.size() > 0) {
//                    Integer uid = clubActivityList.get(0).getUid();
//                    RespUserInfoBase userInfoBase = getUserInfoBase(uid);
//                    if (userInfoBase != null) {
//                        detail.setCreaterName(userInfoBase.getNickName());
//                    }
//                }
//
//            }
//            //活动线上收入
//            BigDecimal totalAmount = BigDecimal.ZERO;
//            TbClubOnlineAccountStreamExample example = new TbClubOnlineAccountStreamExample();
//            example.createCriteria().andClubIdEqualTo(clubId).andActivityIdEqualTo(settlement.getActivityId()).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
//            List<TbClubOnlineAccountStream> onlinestreams = clubOnlineAccountStreamMapper.selectByExample(example);
//            if (onlinestreams != null && onlinestreams.size() > 0) {
//                BigDecimal income = onlinestreams.get(0).getIncomeOnline();
//                totalAmount = totalAmount.add(income);
//                detail.setOnlineAmount(income);
//            }
//            //活动线下收入
//            TbClubOfflineAccountStreamExample example2 = new TbClubOfflineAccountStreamExample();
//            example2.createCriteria().andClubIdEqualTo(clubId).andActivityIdEqualTo(settlement.getActivityId()).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
//            List<TbClubOfflineAccountStream> offlinestreams = clubOfflineAccountStreamMapper.selectByExample(example2);
//            if (offlinestreams != null && offlinestreams.size() > 0) {
//                BigDecimal income = offlinestreams.get(0).getIncomeOffline();
//                totalAmount = totalAmount.add(income);
//                detail.setOfflineAmount(income);
//            }
//            //活动报名人数
//            TbSignUserExample example3 = new TbSignUserExample();
//            example3.createCriteria().andActivityIdEqualTo(settlement.getActivityId())
//                    .andIsCancelEqualTo(Constants.ZERO).andStatusEqualTo(Constants.IS_YES);
//            int count = signUserMapper.countByExample(example3);
//            detail.setNumberOfPeople(count);
//            detail.setAmount(totalAmount);
//            detail.setIncomeFrom("活动收入");
//            detail.setCreateTime(settlement.getCreateTime());
//            details.add(detail);
        }
        return details;
    }

    /**
     * 调用运动场服务，查询俱乐部赛事活动账单信息
     */
    private RespClubFinanceBillDetail getClubGameFinanceBillDetail(Integer activityId, Integer clubId) {
        RespClubFinanceBillDetail detail = new RespClubFinanceBillDetail();
        RespGameDetail gameDetail = stadiumOpenService.getGameDetailByGameId(activityId);
        if (gameDetail == null) {
            return null;
        }
        detail.setActivityId(activityId);
        Integer uid = gameDetail.getUid();
        RespUserInfoBase userInfoBase = getUserInfoBase(uid);
        if (userInfoBase != null) {
            detail.setCreaterName(userInfoBase.getNickName());
            detail.setAvatar(userInfoBase.getIcon());
        }
        detail.setActivityName(gameDetail.getName());
        Integer signCount = gameDetail.getTeamLimitNum() - gameDetail.getInventoryLevel();
        BigDecimal amount = gameDetail.getPrice().multiply(new BigDecimal(signCount));
        detail.setOnlineAmount(gameDetail.getPrice());
        detail.setOfflineAmount(BigDecimal.ZERO);
        detail.setNumberOfPeople(signCount);
        detail.setAmount(amount);
        detail.setIncomeFrom("俱乐部赛事收入");
        detail.setCreateTime(gameDetail.getCreateTime());
        return detail;
    }

    @Override
    public RespClubFinanceBillDetail getClubFinanceBillDetail(@NotNull Integer activityId,
                                                              @NotNull Integer clubId,
                                                              @NotNull Integer type) {

        TbClubActivitySettlementExample settlementExample = new TbClubActivitySettlementExample();
        settlementExample.createCriteria().andActivityIdEqualTo(activityId)
                .andClubIdEqualTo(clubId).andTypeEqualTo(type);
        List<TbClubActivitySettlement> settlements =
                clubActivitySettlementMapper.selectByExample(settlementExample);
        if (CollectionUtils.isEmpty(settlements)) {
            logger.warn("没有活动结算详情，clubActivitySettlement is null。");
            return null;
        }

        TbClubActivitySettlement settlement = settlements.get(0);

        RespClubFinanceBillDetail detail = new RespClubFinanceBillDetail();

        //活动基本信息
        detail.setActivityId(settlement.getActivityId());
        ActivityInfo activity = activityOpenService.queryOneActivityById(settlement.getActivityId());
        if (activity == null) {
            logger.warn("没有活动详情，activity is null。");
            return null;
        }

        TbActivityPoster poster = posterMapper.selectByPrimaryKey(activity.getPosterPicId());
        detail.setAvatar(poster.getUrl());
        detail.setActivityName(activity.getName());

        TbClubActivityExample tbClubActivityExample = new TbClubActivityExample();
        tbClubActivityExample.createCriteria()
                .andActivityIdEqualTo(activity.getId())
                .andClubIdEqualTo(clubId)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubActivity> clubActivityList =
                clubActivityMapper.selectByExample(tbClubActivityExample);
        if (CollectionUtils.isEmpty(clubActivityList)) {
            logger.warn("没有活动列表，clubActivityList is null。");
            return null;
        }

        Integer uid = clubActivityList.get(0).getUid();
        RespUserInfoBase userInfoBase = getUserInfoBase(uid);
        if (userInfoBase != null) {
            detail.setCreaterName(userInfoBase.getNickName());
        }

        //活动线上收入
        BigDecimal totalAmount = BigDecimal.ZERO;
        TbClubOnlineAccountStreamExample onlineAccountStreamExample
                = new TbClubOnlineAccountStreamExample();
        onlineAccountStreamExample.createCriteria().andClubIdEqualTo(clubId)
                .andActivityIdEqualTo(settlement.getActivityId())
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubOnlineAccountStream> onlineStreams =
                clubOnlineAccountStreamMapper.selectByExample(onlineAccountStreamExample);
        if (CollectionUtils.isNotEmpty(onlineStreams)) {
            BigDecimal income = onlineStreams.get(0).getIncomeOnline();
            totalAmount = totalAmount.add(income);
            detail.setOnlineAmount(income);
        }

        //活动线下收入
        TbClubOfflineAccountStreamExample offlineAccountStreamExample
                = new TbClubOfflineAccountStreamExample();
        offlineAccountStreamExample.createCriteria().andClubIdEqualTo(clubId)
                .andActivityIdEqualTo(settlement.getActivityId())
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubOfflineAccountStream> offlineStreams =
                clubOfflineAccountStreamMapper.selectByExample(offlineAccountStreamExample);
        if (CollectionUtils.isNotEmpty(offlineStreams)) {
            BigDecimal income = offlineStreams.get(0).getIncomeOffline();
            totalAmount = totalAmount.add(income);
            detail.setOfflineAmount(income);
        }

        //活动报名人数
        TbSignUserExample tbSignUserExample = new TbSignUserExample();
        tbSignUserExample.createCriteria().andActivityIdEqualTo(
                settlement.getActivityId()).andIsCancelEqualTo(Constants.ZERO)
                .andStatusEqualTo(Constants.IS_YES);
        int count = signUserMapper.countByExample(tbSignUserExample);
        detail.setNumberOfPeople(count);
        detail.setAmount(totalAmount);
        detail.setIncomeFrom("活动收入");
        detail.setCreateTime(settlement.getCreateTime());
        return detail;
    }


    /**
     * 获取俱乐部月度结算活动的个数
     *
     * @param clubId 俱乐部ID
     * @param month  月份
     */
    @Override
    public Integer countClubFinanceBillDetails(@NotNull Integer clubId, @NotNull @DateTimeFormat(pattern = "yyyy-MM") Date month) {
        TbClubActivitySettlementExample settlementExample = new TbClubActivitySettlementExample();  //查询出一个月内某俱乐部已结算的活动
        settlementExample.createCriteria().andClubIdEqualTo(clubId)
                .andCreateTimeGreaterThanOrEqualTo(month).andCreateTimeLessThan(DateUtils.addMonth(month, 1));
        return clubActivitySettlementMapper.countByExample(settlementExample);
    }

    /**
     * 计算某俱乐部在时间段内的线上收入
     *
     * @param clubId 俱乐部ID
     * @param start  开始时间
     * @param end    结束时间
     */
    @Override
    public BigDecimal getClubOnlineFund(@NotNull Integer clubId, Date start, Date end) {
        //计算线上收入
        TbClubOnlineAccountStreamExample clubOnlineAccountExample = new TbClubOnlineAccountStreamExample();
        TbClubOnlineAccountStreamExample.Criteria criteria = clubOnlineAccountExample.createCriteria();
        criteria.andClubIdEqualTo(clubId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        if (start != null) {
            criteria.andCreateTimeGreaterThanOrEqualTo(start);
        }
        if (end != null) {
            criteria.andCreateTimeLessThan(end);
        }
        List<TbClubOnlineAccountStream> streams = clubOnlineAccountStreamMapper.selectByExample(clubOnlineAccountExample);
        BigDecimal onlineTotalFund = BigDecimal.ZERO;
        if (streams != null && streams.size() > 0) {
            for (TbClubOnlineAccountStream stream : streams) {
                BigDecimal income = stream.getIncomeOnline();
                BigDecimal output = stream.getOutputOnline();
                if (income != null) {
                    onlineTotalFund = onlineTotalFund.add(income);      //俱乐部收入
                }
                if (output != null && stream.getType() != 0 && stream.getType() != -1) { //排除提现的
                    onlineTotalFund = onlineTotalFund.add(new BigDecimal(-1 * output.floatValue()));  //俱乐部支出
                }
            }
        }
        return onlineTotalFund;
    }

    /**
     * 计算某俱乐部在时间段内的线下收入
     *
     * @param clubId 俱乐部ID
     * @param start  开始时间
     * @param end    结束时间
     */
    @Override
    public BigDecimal getClubOfflineFund(Integer clubId, Date start, Date end) {
        //计算线下收入
        TbClubOfflineAccountStreamExample example = new TbClubOfflineAccountStreamExample();
        TbClubOfflineAccountStreamExample.Criteria criteria = example.createCriteria();
        criteria.andClubIdEqualTo(clubId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        if (start != null) {
            criteria.andCreateTimeGreaterThanOrEqualTo(start);
        }
        if (end != null) {
            criteria.andCreateTimeLessThan(end);
        }
        List<TbClubOfflineAccountStream> streams = clubOfflineAccountStreamMapper.selectByExample(example);
        BigDecimal offlineTotalFund = BigDecimal.ZERO;
        if (streams != null && streams.size() > 0) {
            for (TbClubOfflineAccountStream stream : streams) {
                BigDecimal income = stream.getIncomeOffline();
                BigDecimal output = stream.getOutputOffline();
                if (income != null) {
                    offlineTotalFund = offlineTotalFund.add(income);      //俱乐部收入
                }
                if (output != null) {
                    offlineTotalFund = offlineTotalFund.add(new BigDecimal(-1 * output.floatValue()));  //俱乐部支出
                }
            }
        }
        return offlineTotalFund;
    }

    /**
     * 获取俱乐部未结算资金
     *
     * @param clubId 俱乐部ID
     */
    @Override
    public BigDecimal getClubUnsettlmentActivityTotalFund(Integer clubId) {
        BigDecimal totalFund = BigDecimal.ZERO;
        TbClubActivityExample example = new TbClubActivityExample();
        example.createCriteria().andClubIdEqualTo(clubId).andIsSettleIn(Arrays.asList((byte) 0, (byte) 2)); //未结算的活动

        List<TbClubActivity> clubActivities = clubActivityMapper.selectByExample(example);

        for (TbClubActivity activity : clubActivities) {
            BigDecimal income = getForincome(activity.getActivityId());
            totalFund = totalFund.add(income);
        }
        return totalFund;
    }

    /**
     * 获取俱乐部未结算的活动列表（分页）
     *
     * @param clubId   俱乐部ID
     * @param pageNo   页码
     * @param pageSize 每页记录条数
     */
    @Override
    public List<RespClubUnsettlementActivity> getClubUnsettlementActivities(Integer clubId, Integer pageNo, Integer pageSize) {
        List<RespClubUnsettlementActivity> list = new ArrayList<>();
        Limit limit = Limit.buildLimit(pageNo, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("clubId", clubId);
        map.put("pageStart", limit.getStart());
        map.put("pageSize", limit.getSize());
        List<RespClubActivity> respClubActivities =
                clubActivityCRUDMapper.queryUnSettlementActivity(map);
        if (respClubActivities != null && respClubActivities.size() > 0) {
            for (RespClubActivity activity : respClubActivities) {
                RespClubUnsettlementActivity respActivity = new RespClubUnsettlementActivity();
                respActivity.setActivityId(activity.getActivityId());
                TbActivityPoster poster = posterMapper.selectByPrimaryKey(activity.getPosterPicId());
                if (poster != null) {
                    respActivity.setActivityImageUrl(poster.getUrl());   //活动海报
                }
                respActivity.setActivityName(activity.getName());
                RespCity city = getCity(activity.getCityId());
                if (city != null) {
                    respActivity.setActivityPlace(city.getName());
                } else {
                    respActivity.setActivityPlace(activity.getPlaceAddress());
                }
                respActivity.setIsSettle(activity.getIsSettle().byteValue());
                respActivity.setStartTime(activity.getStartTime());
                respActivity.setEndTime(activity.getEndTime());
                respActivity.setForincome(getForincome(activity.getActivityId()));
                respActivity.setFeeType(activity.getFeeType());
                respActivity.setFemaleFee(activity.getFemaleFee());
                respActivity.setAaFee(activity.getAaFee());
                respActivity.setMaleFee(activity.getMaleFee());
                respActivity.setFemaleMemberFee(activity.getFemaleMemberFee());
                respActivity.setMaleMemberFee(activity.getMaleMemberFee());
                respActivity.setSignUserList(getSignUserAvatars(activity.getActivityId()));
                if (null != activity.getPlaceId() && activity.getPlaceId() != 0) {
                    try {
                        Map<Integer, PlaceDubboProvider> placeMap =
                                placeClient.getPlaceBySinglePlaceId(activity.getPlaceId());
                        if (null != map && map.containsKey(activity.getPlaceId())) {
                            PlaceDubboProvider placeDubboProvider = placeMap.get(activity.getPlaceId());
                            if (null != placeDubboProvider) {
                                respActivity.setActivityAddress(placeDubboProvider.getName());
                            }
                            map.clear();
                        }
                    } catch (RpcException re) {
                        logger.warn("调用场馆返回空值。" + re.getMessage());
                    }
                }else {
                    respActivity.setActivityAddress(activity.getPlaceAddress());
                }
                list.add(respActivity);
            }
        }
        return list;
    }

    /**
     * 获取某个为结算的活动的活动收入总额
     */
    private BigDecimal getForincome(Integer activityId) {
        TbSignUserExample tbSignUserExample = new TbSignUserExample();
        tbSignUserExample.createCriteria()
                .andManageTypeIn(Arrays.asList(0,4))
                .andActivityIdEqualTo(activityId).andStatusEqualTo(1).andIsCancelEqualTo(0);
        List<TbSignUser> signUsers = signUserMapper.selectByExample(tbSignUserExample);
        List<Integer> orderIds = new ArrayList<Integer>();
        for(TbSignUser signUser : signUsers)
        {
            if(null != signUser.getOrderId() && signUser.getOrderId() > 0)
            {
                orderIds.add(signUser.getOrderId());
            }
        }
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andActivityIdEqualTo(activityId).andOrderStatusIn(Lists.newArrayList((byte) 2, (byte)6, (byte) 7))
                .andCancelTypeEqualTo(Constants.BYTE_ZERO)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbOrder> orders = orderMapper.selectByExample(example);
        BigDecimal total = BigDecimal.ZERO;
        if (orders != null && orders.size() > 0) {
            for (TbOrder order : orders) {
                if(CollectionUtils.isNotEmpty(orderIds))
                {
                    logger.warn("orderId：" + order.getId());
                    if(orderIds.contains(order.getId()))
                    {
                        total = total.add(order.getOrderAmount());
                    }
                }
            }
        }
        return total;
    }

    /**
     * 获取活动地点: “城市名 地区名”
     *
     * @param cityId     活动所在城市ID
     * @param districtId 活动所在区域ID
     */
    private String getActivityPlace(Integer cityId, Integer districtId) {
        StringBuilder place = new StringBuilder();
        RespCity city = getCity(cityId);
        if (city != null) {
            place.append(city.getName());
        }
        RespDistrict district = getDistrict(districtId);
        if (district != null) {
            place.append(" ");
            place.append(district.getName());
        }
        return place.toString();
    }

    /**
     * 获取活动报名人的头像，游客用默认头像
     *
     * @param activityId 活动ID
     */
    private List<String> getSignUserAvatars(Integer activityId) {
        List<String> avatars = new ArrayList<>();
        TbSignUserExample example = new TbSignUserExample();
        example.createCriteria().andActivityIdEqualTo(activityId).andIsCancelEqualTo(Constants.ZERO).andStatusEqualTo(Constants.IS_ACTIVE); //未取消并且支付
        List<TbSignUser> signUsers = signUserMapper.selectByExample(example);
        if (signUsers != null && signUsers.size() > 0) {
            for (TbSignUser signUser : signUsers) {
                Integer order_uid = signUser.getOrderUserId();
                if (order_uid == null || order_uid == 0) {
                    int gender = signUser.getGender();
                    if (gender == Constants.GENDER_FEMALE) {
                        avatars.add("");    //女默认头像
                    } else if (gender == Constants.GENDER_MALE) {
                        avatars.add("");    //男默认头像
                    }
                } else {
                    APIResponse<RespUserInfoBase> response = userServiceFacade.queryUserInfo(order_uid);
                    if (response != null && response.isRet()) {
                        RespUserInfoBase uinfo = response.getData();
                        avatars.add(uinfo.getIcon());
                    }
                }
            }
        }
        return avatars;
    }

    /**
     * 获取俱乐部未结算的活动个数
     *
     * @param clubId 俱乐部ID
     */
    @Override
    public Integer countClubUnsettlementActivities(Integer clubId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("clubId", clubId);
        return clubActivityCRUDMapper.countUnSettlementActivity(map);
    }

    /**
     * 获取俱乐部成员账户列表 （分页）
     *
     * @param clubId   俱乐部ID
     * @param pageNo   页码
     * @param pageSize 每页记录条数
     */
    @Override
    public List<RespClubMemberAccount> getClubMemberAccounts(@NotNull Integer clubId,
                                                             @NotNull Integer pageNo,
                                                             @NotNull Integer pageSize,
                                                             String appVersion) {

        List<RespClubMemberAccount> accounts = new ArrayList<>();// sqlSessionTemplate.selectList("selectClubMemberAccounts", clubId, new RowBounds((pageNo-1)*pageSize, pageSize));
        TbClubOnlineMemberAccountExample example = new TbClubOnlineMemberAccountExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        example.setLimit(Limit.buildLimit(pageNo, pageSize));
        List<TbClubOnlineMemberAccount> onlineMemberAccounts = clubOnlineMemberAccountMapper.selectByExample(example);
        if (onlineMemberAccounts == null || onlineMemberAccounts.size() <= 0) {
            return accounts;
        }
        //填充俱乐部成员用户信息：姓名，头像
        for (TbClubOnlineMemberAccount onlineMemberAccount : onlineMemberAccounts) {
            int uid = onlineMemberAccount.getUid();
            RespClubMemberAccount account = new RespClubMemberAccount();
            account.setUid(uid);
            RespUserInfoBase userInfo = getUserInfoBase(uid);
            if (userInfo == null) {
                continue;
            }
            account.setAvatar(userInfo.getIcon());
            account.setName(userInfo.getNickName());
            TbClubMember clubMember = this.getClubMember(uid, clubId);
            if (clubMember != null) {
                account.setRoleName(clubMember.getRoleName());
            }
            account.setOnlineFund(onlineMemberAccount.getMoneyTotal());
            if(VersionUtils.compareVersion(appVersion, "2.2") < 0)
            {
                TbClubOfflineMemberAccount offlineAccount = getClubMemberOfflineAccount(uid, clubId);
                if (offlineAccount != null) {
                    account.setOfflineFund(offlineAccount.getMoneyTotal());
                } else {
                    account.setOfflineFund(BigDecimal.ZERO);
                }
            }
            accounts.add(account);
        }
        return accounts;
    }

    /**
     * 获取俱乐部成员账户总个数
     *
     * @param clubId 俱乐部ID
     */
    @Override
    public Integer countClubMemberAccounts(Integer clubId) {
        TbClubOnlineMemberAccountExample example = new TbClubOnlineMemberAccountExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        return clubOnlineMemberAccountMapper.countByExample(example);
    }

    /**
     * 获取俱乐部成员资金总和
     *
     * @param clubId 俱乐部ID
     */
    @Override
    public BigDecimal getClubMemberTotalFund(Integer clubId, String appVersion) {
        BigDecimal total = BigDecimal.ZERO;
        TbClubOnlineMemberAccountExample example1 = new TbClubOnlineMemberAccountExample();
        example1.createCriteria()
                .andClubIdEqualTo(clubId)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubOnlineMemberAccount> onlineMemberAccounts = clubOnlineMemberAccountMapper.selectByExample(example1);
        for (TbClubOnlineMemberAccount account : onlineMemberAccounts) {
            total = total.add(account.getMoneyTotal());
        }
        if(VersionUtils.compareVersion(appVersion, "2.2") < 0);
        {
            TbClubOfflineMemberAccountExample example2 = new TbClubOfflineMemberAccountExample();
            example2.createCriteria()
                    .andClubIdEqualTo(clubId)
                    .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            List<TbClubOfflineMemberAccount> offlineMemberAccounts = clubOfflineMemberAccountMapper.selectByExample(example2);
            for (TbClubOfflineMemberAccount account : offlineMemberAccounts) {
                total = total.add(account.getMoneyTotal());
            }
        }

        return total;
    }

    /**
     * 给俱乐部成员线下充值
     *
     * @param uid    俱乐部成员用户ID
     * @param clubId 俱乐部ID
     * @param amount 充值金额
     * @param remark 备注
     * @return 是否充值成功
     */
    @Override
    @Transactional
    public Boolean clubMemberOfflineFundRecharge(Integer uid, Integer clubId, BigDecimal amount, String remark) {
        TbClubOfflineMemberAccount existAccount = getClubMemberOfflineAccount(uid, clubId);
        BigDecimal preAmount = BigDecimal.ZERO;
        if (existAccount == null) {
            return false;//账户不存在或冻结
        }
        preAmount = existAccount.getMoneyTotal();
        existAccount.setMoneyTotal(existAccount.getMoneyTotal().add(amount));
        existAccount.setRemark(remark);
        int update = clubOfflineMemberAccountMapper.updateByPrimaryKeySelective(existAccount);
        //记入俱乐部成员线下账户流水表
        if (update == Constants.IS_YES) {
            TbClubOfflineMemberAccountStream stream = new TbClubOfflineMemberAccountStream();
            stream.setSerialNo(NumberGenerator.getNextOrderNo());
            stream.setClubId(clubId);
            stream.setUid(uid);
            TbClub club = clubMapper.selectByPrimaryKey(clubId);
            if (club != null) {
                stream.setCheques(club.getClubName());
            }
            stream.setRemark(StringUtil.isBlankOrNull(remark) ? club.getClubName() + "俱乐部会费充值" : remark);
            stream.setStatus(Constants.BYTE_ONE);
            stream.setType(Constants.BYTE_ZERO);
            stream.setPayChannel(Constants.BYTE_ZERO);   //管理员充值/扣费
            stream.setIsDelete(Constants.IS_DELETE_FALSE);
            stream.setTypeIntro("现场充值");
            stream.setPayMode("现金付款");
            stream.setPreAmount(preAmount);
            stream.setIncome(amount);   //俱乐部成员的收入金额
            stream.setSufAmount(preAmount.add(amount));
            stream.setClubOfflineMemberAccountId(existAccount.getId());
            stream.setSource("offline");
            int ret = clubOfflineMemberAccountStreamMapper.insertSelective(stream);
            if (ret == Constants.IS_YES) {
                // 发送充值成功的消息给俱乐部成员
                cppService.pushOfflineRechargeDebutMsg(clubId, uid, amount, preAmount.add(amount), remark, true);
                return true;    //生成流水成功
            }
        }
        return false;
    }

    /**
     * 给俱乐部成员线下扣费
     *
     * @param uid    俱乐部成员用户ID
     * @param clubId 俱乐部ID
     * @param amount 扣费金额
     * @param remark 备注
     * @return 是否扣费成功
     */
    @Override
    @Transactional
    public Boolean clubMemberOfflineFundDedut(Integer uid, Integer clubId, BigDecimal amount, String remark) {
        TbClubOfflineMemberAccount account = getClubMemberOfflineAccount(uid, clubId);
        if (account == null) {
            return false;
        }
        BigDecimal usableMoney = account.getMoneyTotal();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("clubId", clubId);
        paramMap.put("uid", uid);
        paramMap.put("amount", amount);
        int ret = sqlSessionTemplate.update("updateClubMemberOfflineAccount", paramMap);
        //记入俱乐部成员线下账户流水表
        if (ret == Constants.IS_YES) {
            TbClubOfflineMemberAccountStream stream = new TbClubOfflineMemberAccountStream();
            stream.setSerialNo(NumberGenerator.getNextOrderNo());
            stream.setClubId(clubId);
            stream.setUid(uid);
            stream.setRemark(StringUtil.isBlankOrNull(remark) ? "详情请咨询俱乐部主席" : remark);
            stream.setStatus(Constants.BYTE_ONE);
            stream.setPayChannel(Constants.BYTE_ZERO);   //管理员充值/扣费
            stream.setIsDelete(Constants.IS_DELETE_FALSE);
            stream.setPreAmount(usableMoney);
            stream.setOutput(amount);
            stream.setTypeIntro("现场消费");
            TbClub club = clubMapper.selectByPrimaryKey(clubId);
            if (club != null) {
                stream.setCheques(club.getClubName());
            }
            stream.setPayMode("俱乐部管理员扣费");
            BigDecimal sufAmount = usableMoney.add(new BigDecimal(-1 * amount.floatValue()));
            stream.setSufAmount(sufAmount);
            stream.setType(Constants.BYTE_ONE);
            stream.setClubOfflineMemberAccountId(account.getId());
            stream.setSource("offline");
            int insert = clubOfflineMemberAccountStreamMapper.insertSelective(stream);
            if (insert == Constants.IS_YES) {
                // 发送扣费成功的消息给俱乐部成员
                cppService.pushOfflineRechargeDebutMsg(clubId, uid, amount, sufAmount, remark, false);
                return true;    //生成流水成功
            }
        }
        return false;
    }

    /**
     * 判断局部成员是否在俱乐部中存在账户
     *
     * @param uid    俱乐部成员用户ID
     * @param clubId 俱乐部ID
     */
    @Override
    public TbClubOfflineMemberAccount getClubMemberOfflineAccount(Integer uid, Integer clubId) {
        TbClubOfflineMemberAccountExample example = new TbClubOfflineMemberAccountExample();
        example.createCriteria().andClubIdEqualTo(clubId).andUidEqualTo(uid).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubOfflineMemberAccount> accounts = clubOfflineMemberAccountMapper.selectByExample(example);
        if (accounts != null && accounts.size() > 0) {
            return accounts.get(0);
        }
        return null;
    }

    /**
     * 获取某个用在俱乐部中的线上账户
     */
    public TbClubOnlineMemberAccount getClubMemberOnlineAccount(Integer uid, Integer clubId) {
        TbClubOnlineMemberAccountExample example = new TbClubOnlineMemberAccountExample();
        example.createCriteria().andClubIdEqualTo(clubId).andUidEqualTo(uid).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubOnlineMemberAccount> accounts = clubOnlineMemberAccountMapper.selectByExample(example);
        if (accounts != null && accounts.size() > 0) {
            return accounts.get(0);
        }
        return null;
    }

    /**
     * 获取俱乐部成员账单流水
     *
     * @param uid      用户ID
     * @param clubId   俱乐部ID
     * @param pageNo   页码
     * @param pageSize 每页条数
     * @return 个人账单流水
     */
    @Override
    public List<RespClubMemberBillInfo> getClubMemberBillInfos(Integer uid, Integer clubId, Integer pageNo, Integer pageSize) {
        //TODO sqlSessionTemplate.selectList("", )
        return null;
    }


    /**------------------------------------------------------线上资金操作-----------------------------------------------------------**/


    /**
     * 俱乐部成员线上充值
     */
    @Override
    public APIResponse<RespPreOrder> memberRecharge(ReqClubMemberRecharge reqClubMemberRecharge, int uid, String userClientIp, HttpServletRequest request) {

        int clubId = reqClubMemberRecharge.getClubId();
        BigDecimal money = reqClubMemberRecharge.getMoney();
        int payChannel = reqClubMemberRecharge.getPayChannel();
        int platformType = reqClubMemberRecharge.getPlatformType();
        String ver = request.getHeader("APPVersion");
        StringBuffer remark = new StringBuffer();
        //获取俱乐部信息
        TbClub club = super.getClub(clubId);
        if (club != null) {
            remark.append(club.getClubName()).append("会费充值");
        }
        //将充值信息存入数据库
        TbClubOnlineMemberAccount clubOnlineMemberAccount = this.getClubOnlineMemberAccount(clubId, uid);

        if (clubOnlineMemberAccount != null) {

            //收支类型：0为充值，1为消费，2为退款',
            int type = 0;
            //信息存入俱乐部成员线上账户流水:
            //初始化时将变动前金额和变动后金额置为0，账户充值完成时再将变动前金额和变动后金额修改为相应的金额
            TbClubOnlineMemberAccountStream clubOnlineMemberAccountStream = this.insertClubOnlineMemberAccountStream(
                    uid,
                    0,
                    clubId,
                    0,
                    money,
                    payChannel,
                    remark.toString(),
                    type,
                    BigDecimal.ZERO,
                    BigDecimal.ZERO,
                    0,
                    "百灵鸟",
                    "",
                    "在线充值",
                    platformType);
            if (clubOnlineMemberAccountStream != null) {
                APIResponse<RespPreOrder> response = this.insertOnlineOrder(
                        uid,
                        remark.toString(),
                        money,
                        payChannel,
                        clubOnlineMemberAccountStream.getOutTradeNo(),
                        userClientIp,
                        clubId,
                        platformType,
                        request,
                        ver);
                if (response.isRet()) {
                    //0:待处理 1：处理成功 2处理中 3：处理失败
                    this.updateClubOnlineMemberAccountStream(2, clubOnlineMemberAccountStream.getId());
                    return response;
                } else {
                    logger.error("支付系统调起失败：{}", response.getErrmsg());
                    return APIResponse.returnFail("支付系统调起失败");
                }
            } else {
                return APIResponse.returnFail("充值记录插入失败");
            }
        } else {
            return APIResponse.returnFail("您充值的账户不存在");
        }
    }

    /**
     * 俱乐部成员余额
     */
    @Override
    public RespClubMemberRemainder memberRemainder(int clubId, int uid) {
//        Map map = new HashMap();
//        map.put("clubId", clubId);
//        map.put("uid", uid);
        RespClubMemberRemainder remainder =  new RespClubMemberRemainder();//clubAccountExtendMapper.memberRemainder(map);
//        if (null != remainder) {
//            remainder.setClubId(clubId);
//        }
        remainder.setClubId(clubId);
        remainder.setOfflineMoneyTotal(BigDecimal.ZERO);
        TbClubOnlineMemberAccountExample example = new TbClubOnlineMemberAccountExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andUidEqualTo(uid)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubOnlineMemberAccount> clubOnlineMemberAccounts = clubOnlineMemberAccountMapper.selectByExample(example);
        if (clubOnlineMemberAccounts != null && clubOnlineMemberAccounts.size() != 0) {
            remainder.setOnlineMoneyTotal(clubOnlineMemberAccounts.get(0).getMoneyTotal());
        }else {
            remainder.setOnlineMoneyTotal(BigDecimal.ZERO);
        }
        return remainder;
    }

    /**
     * 俱乐部成员账户明细
     */
    @Override
    public PageObj<RespClubMemberAccountStream> memberStream(ReqClubMemberAccountStreamPage reqClubMemberAccountStreamPage, int uid) {
        int clubId = (int) reqClubMemberAccountStreamPage.getParamMap().get("clubId");
        Integer currentUid = null;
        if (reqClubMemberAccountStreamPage.getParamMap().containsKey("currentUid")) {
            currentUid = (int) reqClubMemberAccountStreamPage.getParamMap().get("currentUid");
        }
        int pageSize = reqClubMemberAccountStreamPage.getPageSize();
        int pageNum = reqClubMemberAccountStreamPage.getPageNum();
        //pageNum = pageNum > 0 ? pageNum : 1;
        int pageStart = (pageNum) * pageSize;
        Map map = new HashMap();
        if (null == currentUid) {
            map.put("uid", uid);
        } else {
            map.put("uid", currentUid);
        }
        //只展示处理成功的订单
        map.put("status", 1);
        map.put("clubId", clubId);
        int total = this.clubAccountExtendMapper.memberAccountStreamCount(map);
        map.put("pageStart", pageStart);
        map.put("pageSize", pageSize);
        List<TbClubOnlineMemberAccountStream> clubOnlineMemberAccountStreamList = this.clubAccountExtendMapper.memberAccountStream(map);
        List item;
        if (clubOnlineMemberAccountStreamList.isEmpty()) {
            item = new ArrayList<>();
        } else {
            item = new ArrayList<>();
            RespClubMemberAccountStream respClubMemberAccountStream;
            for (TbClubOnlineMemberAccountStream tbClubOnlineMemberAccountStream : clubOnlineMemberAccountStreamList) {
                respClubMemberAccountStream = new RespClubMemberAccountStream();
                respClubMemberAccountStream.setCreateTime(tbClubOnlineMemberAccountStream.getCreateTime().getTime());
                respClubMemberAccountStream.setId(tbClubOnlineMemberAccountStream.getId());
                respClubMemberAccountStream.setRemark(tbClubOnlineMemberAccountStream.getRemark());
                respClubMemberAccountStream.setRemainder(tbClubOnlineMemberAccountStream.getSufAmount());
                int type = tbClubOnlineMemberAccountStream.getType();
                respClubMemberAccountStream.setType(type);
                if (type == ClubConstants.RECHARGE) {
                    respClubMemberAccountStream.setTypeName("收入");
                    respClubMemberAccountStream.setMoney(tbClubOnlineMemberAccountStream.getIncome());
                } else if (type == ClubConstants.CONSUME) {
                    respClubMemberAccountStream.setTypeName("支出");
                    respClubMemberAccountStream.setMoney(tbClubOnlineMemberAccountStream.getOutput());
                } else if (type == ClubConstants.REFUND) {
                    respClubMemberAccountStream.setTypeName("收入");
                    respClubMemberAccountStream.setMoney(tbClubOnlineMemberAccountStream.getIncome());
                } else {
                    respClubMemberAccountStream.setTypeName("其他");
                }
                respClubMemberAccountStream.setTypeIntro(tbClubOnlineMemberAccountStream.getTypeIntro());
                respClubMemberAccountStream.setSource(tbClubOnlineMemberAccountStream.getSource());
                respClubMemberAccountStream.setClubId(tbClubOnlineMemberAccountStream.getClubId());
                item.add(respClubMemberAccountStream);
            }
        }
        PageObj pageObj = PageObj.create(total, pageNum, pageSize, item);
        return pageObj;
    }

    /**
     * 俱乐部成员账户明细详情
     */
    @Override
    public APIResponse<RespClubMemberAccountDetail> memberDetail(String source, int id, int uid, int clubId) {
        //判断该成员是否有权限查看
        TbClubMember clubMember = this.getClubMember(uid, clubId);
        if (null == clubMember) {
            return APIResponse.returnFail("您没有查看权限");
        } else {
            RespClubMemberAccountDetail detail = new RespClubMemberAccountDetail();
            //判断是线下账户还是线上账户
            if ("online".equals(source)) {
                //获取账户详情
                TbClubOnlineMemberAccountStream onlineStream = this.getClubOnlineMemberAccountStream(id);
                if (null == onlineStream) {
                    return APIResponse.returnFail("该账户明细不存在");
                } else {
                    int type = onlineStream.getType();
                    detail.setTypeIntro(onlineStream.getTypeIntro());
                    detail.setType(type);

                    if (type == 0 || type == 2) { //收支类型：0为充值、2为退款
                        detail.setMoney(onlineStream.getIncome());
                    } else if (type == 1) {    //收支类型：1为消费
                        detail.setMoney(onlineStream.getOutput());
                    }
                    detail.setCheques(onlineStream.getCheques());
                    detail.setCreateTime(onlineStream.getCreateTime().getTime());
                    detail.setId(onlineStream.getId());
                    detail.setPayMode(onlineStream.getPayMode());
                    detail.setRemark(onlineStream.getRemark());
                    detail.setSerialNo(onlineStream.getSerialNo());

                    return APIResponse.returnSuccess(detail);
                }
            } else if ("offline".equals(source)) {
                //获取账户详情
                TbClubOfflineMemberAccountStream offlineStream = this.getClubOfflineMemberAccountStream(id);
                if (null == offlineStream) {
                    return APIResponse.returnFail("该账户明细不存在");
                } else {
                    int type = offlineStream.getType();
                    detail.setTypeIntro(offlineStream.getTypeIntro());
                    detail.setType(type);

                    if (type == 0 || type == 2) { //收支类型：0为充值、2为退款
                        detail.setMoney(offlineStream.getIncome());
                    } else if (type == 1) {    //收支类型：1为消费
                        detail.setMoney(offlineStream.getOutput());
                    }
                    detail.setCheques(offlineStream.getCheques());
                    detail.setCreateTime(offlineStream.getCreateTime().getTime());
                    detail.setId(offlineStream.getId());
                    detail.setPayMode(offlineStream.getPayMode());
                    detail.setRemark(offlineStream.getRemark());
                    detail.setSerialNo(offlineStream.getSerialNo());

                    return APIResponse.returnSuccess(detail);
                }
            } else {
                return APIResponse.returnFail("参数有误");
            }

        }
    }

    /**
     * 插入俱乐部成员线上账户流水
     */
    private TbClubOnlineMemberAccountStream insertClubOnlineMemberAccountStream(
            int uid,
            int productId,
            int clubId,
            int status,
            BigDecimal income,
            int payChannel,
            String remark,
            int type,
            BigDecimal preAmount,
            BigDecimal sufAmount,
            int clubOnlineMemberAccountId,
            String cheques,
            String drawee,
            String typeIntro,
            int platformType) {

        TbClubOnlineMemberAccountStream clubOnlineMemberAccountStream = new TbClubOnlineMemberAccountStream();
        clubOnlineMemberAccountStream.setPreAmount(preAmount);
        clubOnlineMemberAccountStream.setSufAmount(sufAmount);
        clubOnlineMemberAccountStream.setProductId(productId);
        clubOnlineMemberAccountStream.setClubOnlineMemberAccountId(clubOnlineMemberAccountId);
        clubOnlineMemberAccountStream.setClubId(clubId);
        clubOnlineMemberAccountStream.setIncome(income);
        clubOnlineMemberAccountStream.setPayChannel((byte) payChannel);
        clubOnlineMemberAccountStream.setRemark(remark);
        clubOnlineMemberAccountStream.setSerialNo(NumberGenerator.getNextOrderNo());
        clubOnlineMemberAccountStream.setUid(uid);
        clubOnlineMemberAccountStream.setStatus((byte) status);
        clubOnlineMemberAccountStream.setType((byte) type);
        clubOnlineMemberAccountStream.setTypeIntro(typeIntro);
        clubOnlineMemberAccountStream.setPlatformType(platformType);
        //生成订单号
        clubOnlineMemberAccountStream.setOutTradeNo(NumberGenerator.getNextOrderNo());
        //收款方
        clubOnlineMemberAccountStream.setCheques(cheques);
        //付款方
        clubOnlineMemberAccountStream.setDrawee(drawee);

        if (payChannel == 1) {  //支付宝
            clubOnlineMemberAccountStream.setPayMode("支付宝充值");
        } else if (payChannel == 2) {  //微信支付
            clubOnlineMemberAccountStream.setPayMode("微信充值");
        }

        int n = clubOnlineMemberAccountStreamMapper.insertSelective(clubOnlineMemberAccountStream);
        if (n > 0) {
            return clubOnlineMemberAccountStream;
        } else {
            return null;
        }
    }

    private int updateClubOnlineMemberAccountStream(int status, int id) {
        TbClubOnlineMemberAccountStream stream = new TbClubOnlineMemberAccountStream();
        stream.setId(id);
        stream.setStatus((byte) status);

        int n = this.clubOnlineMemberAccountStreamMapper.updateByPrimaryKeySelective(stream);

        return n;
    }

    /**
     * 更新俱乐部成员线下账户信息
     */
    private int updateClubOnlineMemberAccount(int uid, int clubId, BigDecimal money) {
        Map map = new HashMap();
        map.put("uid", uid);
        map.put("clubId", clubId);
        map.put("money", money);
        int n = this.clubAccountExtendMapper.updateClubOnlineMemberAccount(map);
        return n;
    }

    /**
     * 通过订单支付模块，调取第三方支付页面
     */
    private APIResponse<RespPreOrder> insertOnlineOrder(int uid,
                                                        String orderDescribe,
                                                        BigDecimal orderAmount,
                                                        int payChannel,
                                                        String outTradeNo,
                                                        String userClientIp,
                                                        Integer clubId,
                                                        Integer platformType,
                                                        HttpServletRequest request,
                                                        String ver) {

        //调用订单支付模块进行充值
        ReqOrderSave orderSave = new ReqOrderSave();

        orderSave.setSourceSystemId(Constants.CLUB_SYSTEM_CODE);
        orderSave.setSourceBusinessId(Constants.CLUB_RECHARGE_CODE);
        //来源：1：app，2：微信，3：其他
        orderSave.setChannelId(1);
        orderSave.setPlatformType(platformType);
        orderSave.setVer(ver);
        try {
            APIResponse<RespUserInfoBase> respUserInfoBase = this.userServiceFacade.queryUserInfo(uid);
            if (respUserInfoBase.isRet() && respUserInfoBase.getData() != null) {
                RespUserInfoBase userInfoBase = respUserInfoBase.getData();
                orderSave.setContactMobile(userInfoBase.getMobile());
                orderSave.setContactName(userInfoBase.getNickName());
            } else {
                orderSave.setContactMobile("");
                orderSave.setContactName("");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户信息获取失败：{}", e.toString());
        }

        String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        //支付成功回调接口
        orderSave.setNotifyURL(serverUrl + clubRechargeCallBackPaySuccess);
        //支付关闭回调接口
        orderSave.setCloseNotifyURL(serverUrl + clubRechargeCallBackPayClose);
        //支付异常退款回调接口
        orderSave.setExceptionRefundNotify(serverUrl + clubRechargeApplyRefund);
        //支付异常退款成功回调接口
        orderSave.setRefundNotifyURL(serverUrl + clubRechargeRefundSuccess);
        orderSave.setExtraParam(clubId.toString());
        //TODO:暂时无需传该字段
        orderSave.setMchId(2);
        //订单金额
        orderSave.setOrderAmount(orderAmount);
        //订单描述
        orderSave.setOrderDescribe(orderDescribe);
        //订单地址
        orderSave.setOrderURL("");
        orderSave.setOutTradeNo(outTradeNo);
        orderSave.setPayNote("用户俱乐部费用充值");
        orderSave.setUserClientIp(userClientIp);
        //支付超时关闭时间
        orderSave.setPayTimeOut(10);
        orderSave.setUid(uid);
        orderSave.setShowURL("");
        orderSave.setBuyerAccount("");
        orderSave.setService("service.club");

        List<ReqProductDetail> reqProductDetailList = new ArrayList<>();
        ReqProductDetail reqProductDetail = new ReqProductDetail();
        reqProductDetail.setShowURL("");
        reqProductDetail.setPrice(orderAmount);
        reqProductDetail.setProductDesc("会员会费充值");
        reqProductDetail.setProductId("0");
        reqProductDetail.setProductName("俱乐部会费");
        reqProductDetail.setProductURL("");
        reqProductDetail.setQuantity(5);
        reqProductDetailList.add(reqProductDetail);
        orderSave.setProductDetailList(reqProductDetailList);

        List<ReqPayInfo> payInfos = new ArrayList<>();
        ReqPayInfo payInfo = new ReqPayInfo();
        payInfo.setAmount(orderAmount);
        //TODO:暂时支持微信公众号、微信、支付宝支付
        if (payChannel == 1) {  //支付宝
            payInfo.setPayId(ClubConstants.PAY_TYPE_ALIPAY);
            payInfo.setPayType("支付宝充值");
        } else if (payChannel == 2) {  //微信支付
            payInfo.setPayId(ClubConstants.PAY_TYPE_WEICHAT);
            payInfo.setPayType("微信充值");
        }
        payInfo.setAmount(orderAmount);
        payInfos.add(payInfo);
        orderSave.setPayInfos(payInfos);
        APIRequest<ReqOrderSave> apiRequest = new APIRequest<>();
        apiRequest.setData(orderSave);
        APIResponse<RespPreOrder> response = this.orderPayService.submitOrder(apiRequest);
        return response;
    }

    /**
     * 获取俱乐部成员线上账户
     */
    public TbClubOnlineMemberAccount getClubOnlineMemberAccount(int clubId, int uid) {
        TbClubOnlineMemberAccountExample clubOnlineMemberAccountExample = new TbClubOnlineMemberAccountExample();
        TbClubOnlineMemberAccountExample.Criteria criteria = clubOnlineMemberAccountExample.createCriteria();
        criteria.andClubIdEqualTo(clubId);
        criteria.andUidEqualTo(uid);
        criteria.andIsDeleteEqualTo(ClubConstants.IS_DELETE_FALSE);
        List<TbClubOnlineMemberAccount> clubOnlineMemberAccountList = this.clubOnlineMemberAccountMapper.selectByExample(clubOnlineMemberAccountExample);
        if (clubOnlineMemberAccountList.isEmpty()) {
            return null;
        } else {
            return clubOnlineMemberAccountList.get(0);
        }
    }

    /**
     * 获取俱乐部成员信息
     */
    public TbClubMember getClubMember(int uid, int clubId) {
        TbClubMemberExample example = new TbClubMemberExample();
        TbClubMemberExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        criteria.andClubIdEqualTo(clubId);
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubMember> clubMemberList = this.clubMemberMapper.selectByExample(example);
        if (clubMemberList.isEmpty()) {
            return null;
        } else {
            return clubMemberList.get(0);
        }
    }

    /**
     * 获取俱乐部成员线上账户流水信息
     */
    private TbClubOnlineMemberAccountStream getClubOnlineMemberAccountStream(int id) {
        TbClubOnlineMemberAccountStream stream = this.clubOnlineMemberAccountStreamMapper.selectByPrimaryKey(id);
        return stream;
    }

    /**
     * 获取俱乐部成员线上账户流水信息
     */
    private TbClubOfflineMemberAccountStream getClubOfflineMemberAccountStream(int id) {
        TbClubOfflineMemberAccountStream stream = this.clubOfflineMemberAccountStreamMapper.selectByPrimaryKey(id);
        return stream;
    }

    private TbClubMsgConsumerRecord getClubMsgConsumerRecord(String msgId) {
        TbClubMsgConsumerRecordExample example = new TbClubMsgConsumerRecordExample();
        TbClubMsgConsumerRecordExample.Criteria criteria = example.createCriteria();

        criteria.andMsgIdEqualTo(msgId);
        List<TbClubMsgConsumerRecord> clubMsgConsumerRecordList = this.clubMsgConsumerRecordMapper.selectByExample(example);
        if (clubMsgConsumerRecordList.isEmpty()) {
            return null;
        } else {
            return clubMsgConsumerRecordList.get(0);
        }

    }

    /**
     * 获取俱乐部成员线上充值明细
     */
    public List<TbClubOnlineMemberAccountStream> getClubOnlineMemberAccountStreamByOutTradeNo(int clubId, int uid, String outTradeNo, byte status) {
        TbClubOnlineMemberAccountStreamExample example = new TbClubOnlineMemberAccountStreamExample();
        TbClubOnlineMemberAccountStreamExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        if (clubId > 0) {
            criteria.andClubIdEqualTo(clubId);
        }
        criteria.andOutTradeNoEqualTo(outTradeNo);
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteria.andStatusEqualTo(status);
        List<TbClubOnlineMemberAccountStream> list = this.clubOnlineMemberAccountStreamMapper.selectByExample(example);
        return list;
    }

}
